package com.automapper.sqlfragment;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.automapper.criterion.Criterion;
import com.automapper.criterion.ExpressionContext;

public class SqlFragmentContext {
	
	private List<SqlFragmentAssembler> sqlFragmentAssemblers = new ArrayList<>();
	private ExpressionContext expressionContext;

	/**
	 * 生成表
	 * @return
	 * @throws Exception
	 */
	public String getTable() throws Exception {
		List<String> tables = new ArrayList<>();
		for (SqlFragmentAssembler sqlFragmentAssembler : sqlFragmentAssemblers) {
			tables.add(sqlFragmentAssembler.getTable());
		}
		
		return StringUtils.join(tables, ",");
	}
	
	/**
	 * 获取列名
	 * @return
	 */
	public String getColumnName() {
		List<String> columnNames = new ArrayList<>();
		for (SqlFragmentAssembler sqlFragmentAssembler : sqlFragmentAssemblers) {
			columnNames.addAll(sqlFragmentAssembler.getColumnNames());
		}
		return StringUtils.join(columnNames, ",");
	}
	
	/**
	 * 生成where的过滤条件
	 * @return
	 */
	public String getCondition() {
		StringBuilder sql = new StringBuilder();
		List<Criterion> simpleExpressionList = expressionContext.getExpressionList();
		for (Criterion expression : simpleExpressionList) {
			sql.append(" and ").append(expression.toSqlString());
		}
		return sql.toString();
	}
	
	/**
	 * 生成分页sql
	 * @param sql
	 * @return
	 */
	public StringBuilder genPage(StringBuilder sql) {
		if (expressionContext.getPageExpression() != null) {
			// 拼装分页
			sql.append(" " + expressionContext.getPageExpression().toSqlString());
		}
		return sql;
	}
	
	/**
	 * SQL查数值
	 * @return
	 */
	public Map<String, Object> getParamMap() {
		return expressionContext.getParamMap();
	}
	
	public SqlFragmentAssembler getDriverSqlFragmentAssembler() {
		SqlFragmentAssembler sqlFragmentAssembler = null;
		if (sqlFragmentAssemblers.size() == 1) {
			sqlFragmentAssembler = sqlFragmentAssemblers.get(0);
		}
		
		for (SqlFragmentAssembler assembler : sqlFragmentAssemblers) {
			if (assembler.getCascadeSqlFragmentAssembler() != null) {
				sqlFragmentAssembler = assembler;
			}
		}
		return sqlFragmentAssembler;
	}
	
	public void setSqlFragmentAssemblers(List<SqlFragmentAssembler> sqlFragmentAssemblers) {
		this.sqlFragmentAssemblers = sqlFragmentAssemblers;
	}

	public void setExpressionContext(ExpressionContext expressionContext) {
		this.expressionContext = expressionContext;
	}
}
